using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading;
using Gko.Wpf.Mvvm.Interfaces;

namespace Gko.Wpf.Mvvm
{
	public abstract class ViewModelContextBase : ServiceContainer, IViewModelContext
	{
		protected ViewModelContextBase()
		{
		}

		protected ViewModelContextBase(IServiceProvider parentProvider)
			: base(parentProvider)
		{
		}

		protected ViewModelContextBase(SynchronizationContext synchronizationContext, IViewFactory viewFactory, IDialogService dialogService)
			: this(synchronizationContext, viewFactory, dialogService, null)
		{
		}

		protected ViewModelContextBase(SynchronizationContext synchronizationContext, IViewFactory viewFactory, IDialogService dialogService, IServiceProvider parentProvider)
			: this(parentProvider)
		{
			this.AddService(synchronizationContext);
			this.AddService(viewFactory);
			this.AddService(dialogService);
		}

		#region IViewModelContext Members

		public SynchronizationContext SynchronizationContext
		{
			get
			{
				return this.GetService<SynchronizationContext>();
			}
		}

		public IViewFactory ViewFactory
		{
			get
			{
				return this.GetService<IViewFactory>();
			}
		}

		public IDialogService DialogService
		{
			get
			{
				return this.GetService<IDialogService>();
			}
		}

		public void AddService<TService>(TService serviceInstance) where TService : class
		{
			var service = this.GetService<TService>();
			if (service != null) {
				this.RemoveService(typeof(TService), true);
			}
			this.AddService(typeof(TService), serviceInstance);
		}

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
		public TService GetService<TService>() where TService : class
		{
			return (TService)this.GetService(typeof(TService));
		}

		#endregion
	}
}